package com.feng.msm.service.impl;

import com.feng.commonutils.R;

import com.feng.msm.component.MsmComponent;
import com.feng.msm.service.MsmService;
import com.feng.msm.utils.RandomUtil;
import com.feng.servicebase.excecption.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class MsmServiceImpl implements MsmService {
    @Autowired
    private MsmComponent smsComponent;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Transactional
    @Override
    public R sendMsm(String phone) {

        //2.如果redis获取不到进行阿里云的发送
        //生成随机值，传递给阿里云进行发送
       String code = RandomUtil.getFourBitRandom();
        try {
            //阿里云发送验证码
            smsComponent.sendSmsCode(code,phone);
            //发送成功后将验证码放到redis中，设置有效时间5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001,"发送验证码失败");
        }
        //调用service发送短信的方法
      return  R.ok();
    }
}
